package com.qianji.petmall.authserver.controller;

import com.alibaba.fastjson.TypeReference;
import com.qianji.common.constant.AuthConstant;
import com.qianji.common.to.MemberResponseVo;
import com.qianji.common.utils.R;
import com.qianji.petmall.authserver.feign.MemberFeignService;
import com.qianji.petmall.authserver.feign.ThirdPartyFeifnService;
import com.qianji.petmall.authserver.service.LoginService;
import com.qianji.petmall.authserver.vo.UserLoginVo;
import com.qianji.petmall.authserver.vo.UserRegisVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author liang zai
 * @date 2022/3/10 11:43
 * @description
 */
@Controller
public class LoginController {

    @Autowired
    private ThirdPartyFeifnService thirdPartyFeifnService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private LoginService loginService;

    @Autowired
    private MemberFeignService memberFeignService;

    @ResponseBody
    @PostMapping("sms/sendCode")
    public R sendCode(@RequestParam("phone")String phone){
       R r = loginService.sendCode(phone);
       return r;
    }

    @PostMapping("/regis")
    public String regis(@Valid UserRegisVo user, BindingResult result, RedirectAttributes attributes){
        if (result.hasErrors()){
            //如果有错误显示错误内容再跳转
            List<FieldError> fieldErrors = result.getFieldErrors();
            Map<String, String> map = fieldErrors.stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            attributes.addFlashAttribute("errors",map);
//            attributes.addAttribute("errors",map);
            //校验出错转发到注册页
            return "redirect:http://auth.petmall.com/reg.html";
        }
        //远程调用注册
        //1、效验验证码
        String code = user.getCode();
        String phone = user.getPhone();
        String redisCode = redisTemplate.opsForValue().get(AuthConstant.SMS_CODE_CACHE_PREFIX+phone);
        if (StringUtils.isNotEmpty(redisCode)){
            // 判断验证码是否正确【有BUG，如果字符串存储有问题，没有解析出code，数据为空，导致验证码永远错误】
            if (code.equals(redisCode.split("_")[0])){
                //验证码正确，删除验证码（不可重复使用）;令牌机制
                redisTemplate.delete(AuthConstant.SMS_CODE_CACHE_PREFIX+phone);
                //验证码通过，真正注册，调用远程服务进行注册【会员服务】
                R r = memberFeignService.regisVo(user);
                if (r.getCode()==0){
                    //成功
                    return "redirect:http://auth.petmall.com/login.html";
                }else {
                    //校验出错转发到注册页
                    Map<String, String> map = new HashMap<>();
                    map.put("msg",r.getData("msg",new TypeReference<String>(){}));
                    attributes.addFlashAttribute("errors",map);
                    return "redirect:http://auth.petmall.com/reg.html";
                }
            }else {
                //验证码错误
                Map<String, String> map = new HashMap<>();
                map.put("code","验证码错误");
                attributes.addFlashAttribute("errors",map);
                //校验出错转发到注册页
                return "redirect:http://auth.petmall.com/reg.html";
            }
        }else {
            //验证码过期
            Map<String, String> map = new HashMap<>();
            map.put("code","验证码过期");
            attributes.addFlashAttribute("errors",map);
            //校验出错转发到注册页
            return "redirect:http://auth.petmall.com/reg.html";
        }
    }
    @PostMapping("/login")
    public String login(UserLoginVo loginVo, RedirectAttributes redirectAttributes, HttpSession session){
        //登录调用远程接口
        R login = memberFeignService.login(loginVo);
        if (login.getCode() == 0){
            //成功放到session中
            MemberResponseVo data = login.getData("data", new TypeReference<MemberResponseVo>() {});
            session.setAttribute(AuthConstant.LOGIN_USER,data);
            return "redirect:http://petmall.com";
        }else {
            //失败
            Map<String, String> map = new HashMap<>();
            map.put("msg",login.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors",map);
            return "redirect:http://auth.petmall.com/login.html";
        }

    }
}
